package com.example.wei.mvp.ui.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import com.example.wei.mvp.R;
import com.example.wei.mvp.base.BaseRVActivity;
import com.example.wei.mvp.util.FileUtil;
import com.sina.common.andpermission.PermissionUtils;
import com.sina.common.andpermission.SettingDialogUtils;
import com.sina.common.andpermission.listener.AndPermissionListener;
import com.sina.common.okhttp.Constant;
import com.example.wei.mvp.component.AppComponent;
import com.example.wei.mvp.component.DaggerMainComponent;
import com.example.wei.mvp.contract.LoginContract;
import com.example.wei.mvp.ui.presenter.LoginPresenter;
import com.example.wei.mvp.util.L;
import com.example.wei.mvp.util.SPUtils;
import com.example.wei.mvp.util.ToastUtil;
import com.githang.statusbar.StatusBarCompat;
import com.google.gson.Gson;
import com.sina.common.okhttp.OkHttpEnqueue;
import com.sina.common.okhttp.OkHttpRequest;
import com.sina.common.okhttp.TaskName;
import com.sina.common.okhttp.bean.HttpResult;
import com.sina.common.okhttp.listener.ISupportOkHttp;
import com.sina.common.util.fileutils.FileUtils;
import com.yanzhenjie.permission.Permission;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Administrator on 2017/12/4 0004.
 */

public class LoginActivity extends BaseRVActivity<LoginPresenter> implements LoginContract.View,ISupportOkHttp<String>{
    @BindView(R.id.et_phone_number)
    EditText etPhoneNumber;
    @BindView(R.id.et_code)
    EditText etCode;
    private Bitmap bitmap;
    private File file;
    private int i=-1;

    @Override
    public int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void innitView() {
        StatusBarCompat.setStatusBarColor(this, Color.parseColor("#00000000"), true);
    }

    @Override
    protected void innitData() {

    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerMainComponent.builder().appComponent(appComponent).build().inject(this);
    }


    @Override
    public void showError(String err) {

    }

    @Override
    public void complete() {

    }

    @OnClick({R.id.btn_send_very_code, R.id.login,R.id.rl_back,R.id.btn_touch})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_send_very_code:
                //长传图片
             readPermission(2);
                break;
            case R.id.login:

             readPermission(1);
//                getLoginSession();
                break;
            case R.id.rl_back:
                finish();
                break;
            case R.id.btn_touch:

                break;
        }
    }
    private void readPermission(final int i){
        PermissionUtils.mustPermission(this, SettingDialogUtils.getRationaleDialog(this, "读取文件"), SettingDialogUtils.getSettingDialog(this, 123), new AndPermissionListener() {
            @Override
            public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {

            }

            @Override
            public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {

            }

            @Override
            public void onAllSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                if (i==1){
                    downLoadPdf();
                }else if (i==2){
                    upLoadImage();
                }
            }

            @Override
            public void onAllFailed(int requestCode, @NonNull List<String> deniedPermissions) {

            }
        }, Permission.STORAGE);
    }

    private void downLoadPdf() {
        Request request = new Request.Builder().url(Constant.DOWNLOAD_PDF).build();
        OkHttpEnqueue.mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                ToastUtil.showToast("文件保存失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String path = getPdfPath();
                InputStream is = response.body().byteStream();
                if(FileUtils.writeFile(path,is)){
                    showPdf(path);
                }else{
                    showError("文件保存失败");
                }
            }
        });
    }
    private  Handler handler=new Handler();
    private void showPdf(final String path){
        handler.post(new Runnable() {
            @Override
            public void run() {
                File file = new File(path);
                Intent i = new Intent(Intent.ACTION_VIEW);
                i.addCategory(Intent.CATEGORY_DEFAULT);
                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK );
                Uri uri;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    uri = FileProvider.getUriForFile(getApplicationContext(), Constant.FILE_PROVIDER, file);
                }else {
                    uri = Uri.fromFile(file);
                }
                i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                i.setDataAndType(uri, "application/pdf");
                Intent intent = Intent.createChooser(i, "Open File");
                try {
                    startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
    }
    /**
     * 上传图片
     */
    private void upLoadImage() {
        try {
            InputStream is = getAssets().open("beauty.png");
            bitmap = BitmapFactory.decodeStream(is);
            file = FileUtil.getFile("beauty.png");
            saveBitmap(file,bitmap);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //1.使用OKhttp上传图片
        // Request request = OkHttpRequest.postRequest(Constant.UPLOAD_IMAGE, "beauty",file);
        // OkHttpEnqueue.newCall(TaskName.UPLOAD_IMAGE_TASK, request, this);

        //2.使用retrofit上传图片
        mPresenter.postImage("8",file);



    }
    public static void saveBitmap(File file, Bitmap bitmap) throws IOException {
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(
                file));
    }

    /**
     * 获取pdf保存路径
     * @return
     */
    private String  getPdfPath(){
        return  FileUtils.externalRootDirectory(this)+File.separator+"sina.pdf";
    }



    //登陆请求
    private void getLoginSession() {
        String phoneNumber = etPhoneNumber.getText().toString().trim();
        if (TextUtils.isEmpty(phoneNumber)) {
            ToastUtil.showToast("请输入正确的电话号码");
            return;
        }
        String codeSms = etCode.getText().toString().trim();
        if (TextUtils.isEmpty(codeSms)) {
            ToastUtil.showToast("请输入正确的短信验证码");
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                RequestBody formBody = new FormBody.Builder()
                        .add("mobile", etPhoneNumber.getText().toString().trim())
                        .add("verify", etCode.getText().toString().trim())
                        .build();
                Request request = new Request.Builder()
                        .url(Constant.LOGIN_VERIFY)
                        .post(formBody)
                        .build();
                try {
                    Response response = new OkHttpClient().newCall(request).execute();
                    if (response.isSuccessful()) {
                        if (response != null) {
                            String header = response.header("Set-Cookie");
                            if (header != null) {
                                String[] strings = header.split(";");
                                if (strings.length > 0) {
                                    SPUtils.put("sessionid", strings[0]);
                                    L.d("sessionid", ">>>>>>>" + strings[0]);
                                }
                            }
                            final String verifyCodeReturn = response.body().string();
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    HttpResult verifyResponse = new Gson().fromJson(verifyCodeReturn, HttpResult.class);
                                    if (verifyResponse.getCode() == 0) {
                                        ToastUtil.showToast("登录成功");
                                        finish();
                                    } else {
                                        if (verifyResponse.getMessage() != null) {
                                            ToastUtil.showToast(verifyResponse.getMessage());
                                        }
                                    }
                                }
                            });
                        }
                    } else {

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    @Override
    public void onSuccess(String task_name, Call call, String result, byte[] bytes, MediaType mediaType) {
        HttpResult httpResult = new Gson().fromJson(result, HttpResult.class);
        if (httpResult.isOk()) {
            if (TaskName.UPLOAD_IMAGE_TASK.equals(task_name)) {
                ToastUtil.showToast(httpResult.getMessage());
            }
        }else {
            ToastUtil.showToast(httpResult.getMessage());
        }
    }

    @Override
    public void onResponse(String task_name, Call call, String result, byte[] bytes, MediaType mediaType) {

    }

    @Override
    public void onFailure(String task_name, Call call, IOException e) {

    }

    @Override
    public void postImage(HttpResult httpResult) {
        if (httpResult.isOk()) {
                ToastUtil.showToast(httpResult.getMessage());
        }else {
            ToastUtil.showToast(httpResult.getMessage());
        }
    }
}
